package com.gee.spring.cloud.data.transform.core.center.config.handler;

import com.gee.spring.cloud.common.core.api.result.ApiResult;
import com.gee.spring.cloud.common.core.entity.center.config.SocketDecoder;
import com.gee.spring.cloud.common.starter.config.event.CenterConfigEventHandler;
import com.gee.spring.cloud.common.starter.feign.center.config.SocketDecoderClient;
import com.gee.spring.cloud.data.transform.core.dispatch.SocketManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gepengjun
 * @since 2024/3/19 14:31
 */
@Component
public class SocketDecoderHandler extends CenterConfigEventHandler<SocketDecoder> {

    private final ConcurrentHashMap<Long, SocketDecoder> SOCKET_DECODER_MAP = new ConcurrentHashMap<>();

    @Autowired
    private SocketDecoderClient socketDecoderClient;

    @Autowired
    private SocketManager socketManager;

    public SocketDecoder getById(Long id){
        return SOCKET_DECODER_MAP.computeIfAbsent(id, newId -> {
            ApiResult<SocketDecoder> apiResult = socketDecoderClient.getById(newId);
            if (! apiResult.isSuccess() || apiResult.getData() == null){
                throw new RuntimeException("未获取到解码器");
            }
            return apiResult.getData();
        });
    }

    @Override
    public void handlerUpdate(List<SocketDecoder> dataList, List<SocketDecoder> oldList) {
        dataList.forEach(socketDecoder -> {
            SOCKET_DECODER_MAP.computeIfPresent(socketDecoder.getId(), (id, old) -> socketDecoder);
            socketManager.updateSocketDecoder(socketDecoder);
        });
    }

    @Override
    public void handlerDelete(List<SocketDecoder> oldList) {
        oldList.forEach(socketDecoder -> SOCKET_DECODER_MAP.remove(socketDecoder.getId()));
    }
}
